const instanceOptions = {
	baseUrl: 'https://www.uinav.com'
}


class ccRequest {
	constructor(options = {}) {
		this.baseUrl = options.baseUrl || ''
		this.url = options.url || ''
		this.method = 'GET'
		this.data = null
		this.hearder = options.hearder || {}
		this.beforeRequest = null
		this.afterRequest = null
		this.timeout = options.timeout || 6000
	}
	get(url, data = {}) {
		this.url = url
		this.data = data
		this.method = 'GET'
		return this.wxajax()
	}
	post(url, data = {}) {
		this.url = url
		this.data = data
		this.method = 'POST'
		return this.wxajax()
	}
	put(url, data = {}) {
		this.method = 'PUT'
		this.url = url
		this.data = data
		return this.wxajax()
	}

	delete(url, data = {}) {
		this.method = 'DELETE'
		this.url = url
		this.data = data
		return this.wxajax()
	}

	wxajax(url = this.url, method = this.method, data = this.data) {
		this.url = url
		this.method = method
		this.data = data
		// 发请求前做的事情
		this.beforeRequest && typeof this.beforeRequest === 'undefined' && this.beforeRequest(this)
		return new Promise((resolve, reject) => {
			let weixin = wx
			// 适配 uniapp
			if ('undefined' !== typeof uni) {
				weixin = uni
			}
			weixin.request({
				url: this.baseUrl + this.url,
				method: this.method,
				header: this.hearder,
				timeout: this.timeout,
				data: this.data,
				success: res => resolve(res),
				fail: err => reject(err),
				complete: res => {
					// 请求完成后做的事情
					this.afterRequest && 'function' === typeof this.afterRequest &&
						this.afterRequest(res)
				}
			})
		})
	}
}



export const $http = new ccRequest(instanceOptions)
